<!-- src/views/ScanPage.vue -->
<template>
  <div class="scan-page">
    <!-- 病虫害扫描区域 -->
    <div class="recognition-container" style="height: 300px;">
      <el-card class="scan-section" style="height: 100%">
        <h2>病虫害扫描</h2>
        <video ref="cropVideo" width="100%" height="100px" autoplay></video>
        <button @click="openCropCamera">打开摄像头</button>
        <button @click="closeCropCamera">关闭摄像头</button>
        <button class="capture-button" :disabled="!isCameraOpen" @click="captureImage">拍摄照片</button>
        <button class="upload-button">
          上传图片
          <input type="file" id="file-input" accept="image/*" @change="handleImageUpload"/>
        </button>
        <p v-if="uploadStatus === 'success'" class="success-text">上传成功</p>
        <p v-if="uploadStatus === 'failure'" class="error-text">上传失败</p>
      </el-card>
    </div>

    <!-- 常见病害新闻列表 -->
    <div class="news-section" style="margin-top: 10px;">
      <h3>常见病虫害</h3>
      <div class="news-item" v-for="news in newsList" :key="news.id">
        <img :src="news.image" alt="新闻图片" class="news-image"/>
        <div class="news-info">
          <el-link type="primary" @click="goToDetailPage(news.link)" class="news-title">{{ news.title }}</el-link>
          <p class="news-meta">{{ news.views }}次阅读 {{ news.date }}</p>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <BottomNav/>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import BottomNav from '@/views/BottomNav.vue'

const router = useRouter()

// 摄像头相关
const cropVideo = ref(null)
const cropVideoStream = ref(null)
const isCameraOpen = ref(false)
const uploadStatus = ref('')

// 新闻数据，每个病虫害添加一个 link 属性
const newsList = [
  {
    id: 1,
    title: '草地贪夜蛾：对玉米、水稻等作物造成严重危害',
    views: '8090',
    date: '2020-12-03',
    image: new URL('@/assets/images/start-page/haichong1.jpg', import.meta.url).href,
    link: '/disease/1'  // 详情页面的链接
  },
  {
    id: 2,
    title: '稻飞虱：通过吸食稻株汁液，导致水稻生长受阻，严重时造成减产。',
    views: '32560',
    date: '2020-12-03',
    image: new URL('@/assets/images/start-page/haichong2.jpg', import.meta.url).href,
    link: '/disease/2'  // 详情页面的链接
  },
  {
    id: 3,
    title: '棉铃虫：主要危害棉花，影响产量和质量。',
    views: '8090',
    date: '2020-12-03',
    image: new URL('@/assets/images/start-page/haichong3.jpg', import.meta.url).href,
    link: '/disease/3'  // 详情页面的链接
  }
]

function openCropCamera() {
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then((stream) => {
        cropVideoStream.value = stream
        cropVideo.value.srcObject = stream
        cropVideo.value.play()
        isCameraOpen.value = true
      })
      .catch((err) => {
        console.error(err)
      })
  } else {
    alert('摄像头不可用')
  }
}

function closeCropCamera() {
  if (cropVideoStream.value) {
    cropVideoStream.value.getTracks()[0].stop()
    cropVideo.value.srcObject = null
    isCameraOpen.value = false
  }
}

function captureImage() {
  if (!isCameraOpen.value) {
    alert('请先打开摄像头')
    return
  }
  const canvas = document.createElement('canvas')
  canvas.width = cropVideo.value.videoWidth
  canvas.height = cropVideo.value.videoHeight
  const ctx = canvas.getContext('2d')
  ctx.drawImage(cropVideo.value, 0, 0, canvas.width, canvas.height)
  const imgData = canvas.toDataURL('image/png')
  saveImage(imgData)
}

function saveImage(imgData) {
  const link = document.createElement('a')
  link.href = imgData
  link.download = 'captured_image.png'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

function handleImageUpload(event) {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = () => {
      const isSuccess = Math.random() > 0.1
      uploadStatus.value = isSuccess ? 'success' : 'failure'
    }
    reader.readAsDataURL(file)
  }
}

function goToDetailPage(path) {
  router.push(path);
}

onBeforeUnmount(() => {
  closeCropCamera()
})
</script>

<style scoped>
.scan-page {
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.recognition-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f7f7;
  padding-bottom: 20px;
}

.scan-section {
  width: 90%;
  margin: 5px 0; /* 减小边距 */
  text-align: center;
}

button {
  margin: 5px 0;
  width: 100px;
  height: 30px; /* 减小按钮高度 */
  background-color: #22ccb3;
  border: none;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #159a8d;
}

.upload-button {
  position: relative;
  overflow: hidden;
}

.upload-button input[type='file'] {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  cursor: pointer;
}

.success-text {
  color: green;
  margin-top: 10px;
}

.error-text {
  color: red;
  margin-top: 10px;
}

.news-section {
  padding: 10px;
  background-color: white;
  border-radius: 8px;
  margin: 10px;
}

.news-section h3 {
  font-size: 16px;
  margin-bottom: 8px;
}

.news-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.news-image {
  width: 70px;
  height: 50px;
  border-radius: 5px;
  margin-right: 8px;
}

.news-info {
  flex: 1;
}

.news-title {
  font-size: 13px;
  margin: 0;
  color: #333;
  line-height: 1.2;
}

.news-meta {
  font-size: 11px;
  color: #808080;
}
</style>
